package com.gxc.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxc.browser.support.SimpleResponse;
import com.gxc.core.config.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author GongXincheng
 * @since 2019-10-15 16:59
 */
@Slf4j
@Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        log.error("登录失败");

        // 如果配置的登录方式为JSON
        String loginType = securityProperties.getBrowser().getLoginType();
        if ("json".equalsIgnoreCase(loginType)) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(exception.getMessage())));
            response.getWriter().flush();
        } else {
            super.onAuthenticationFailure(request, response, exception);
        }

    }
}
